<?php
namespace App\Libraries\Log;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class FczLogger
{
    // 所有的LOG都要求在这里注册
    const LOG_ERROR = 'error';
    const LOG_ORDER = 'order';

    private static $loggers = array();

    // 获取一个实例
    public static function getLogger($type = self::LOG_ERROR, $day = 30)
    {
        if (empty(self::$loggers[$type])) {
            self::$loggers[$type] = new Logger('orderLog',[(new RotatingFileHandler(storage_path("logs/{$type}.log"), $day, Logger::INFO))
                ->setFormatter(new LineFormatter(null, null, true, true))]);
        }
        return self::$loggers[$type];
    }

    public static function error(\Exception $exception,$str,$type=FczLogger::LOG_ERROR)
    {
        if($_SERVER['APP_DEBUG'] == 'true'){
            echo "error see {$type} log";
        }

        $err = "";
        $err .= empty($str) ? "" : 'msg:【'.$str."】\n";
        $err .= 'message: '.$exception->getMessage()."\n";
        $err .= 'file: '.$exception->getFile()." (".$exception->getLine().")\n";
        $err .= 'code: '.$exception->getCode()."\n";
        $err .= 'request: '.$_SERVER['REQUEST_URI']."\n";
        $err .= 'input: '.json_encode(Input::all())."\n";

        FczLogger::getLogger($type)->error($err);

        Log::error($exception);
    }

    public static function orderInfo($order){
        if(empty($order)){
            return ;
        }
        $info = 'order_id:'.$order['order_id'].' status:'.$order['status'].' member_id:'.$order['member_id'].' role:'.$order['role'].' message:'.$order['message'];
        FczLogger::getLogger(FczLogger::LOG_ORDER)->info($info);
    }
}